package Socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public static void main(String[] args) {

        //创建socket
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            while (true){
                //等待连接
                Socket s = serverSocket.accept();
                //发送数据
                //将serverSocket传给子线程，接收数据
                new MyThreadTcp(s).start();

            }







        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}



class MyThreadTcp extends Thread{

    Socket socket;

    public MyThreadTcp(Socket serverSocket) throws IOException {
        this.socket = serverSocket;
    }

    @Override
    public void run() {

        try {
            //接收服务器发来的数据
            InputStream in = socket.getInputStream();
            byte[] bys = new byte[1024];
            int len = in.read(bys);
            String str = new String(bys,0,len,"utf-8");

            System.out.println("客户端发来的数据"+str);

            //获取输出流
            OutputStream os = socket.getOutputStream();
            //发送数据
            String str1 = "hello ,我是服务器";
            os.write(str.getBytes());

            os.flush();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }





}











